import { ResolvedFn, RejectedFn } from '../types/index'
interface Interceptor<T> {
  resolved: ResolvedFn
  rejected?: RejectedFn
}

export default class InterceptorsManager<T> {
  private interceptors: Array<Interceptor<T> | null>
  constructor() {
    this.interceptors = []
  }

  /**
   * 注册拦截器
   *
   * @param {ResolvedFn<T>} resolved
   * @param {RejectedFn} [rejected]
   * @returns {number}
   * @memberof InterceptorsManager
   */
  use(resolved: ResolvedFn<T>, rejected?: RejectedFn): number {
    this.interceptors.push({ resolved, rejected })
    return this.interceptors.length - 1
  }

  /**
   *
   * 取消拦截器
   * @param {number} id
   * @memberof InterceptorsManager
   */
  eject(id: number): void {
    if (this.interceptors[id]) {
      // this.interceptors[id] = null
      this.interceptors.splice(id, 1)
    }
  }

  /**
   * 外部遍历interceptor的接口
   *
   * @param {(interceptor:Interceptor<T>)=> void} fn
   * @memberof InterceptorsManager
   */
  forEach(fn: (interceptor: Interceptor<T>) => void): void {
    this.interceptors.forEach(item => {
      if (item !== null) {
        fn(item)
      }
    })
  }
}
